import sys
import json
import logging
import traceback
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit
from PySide6.QtCore import Qt

CONFIG_PATH = "/home/umeko/scarab/frontend/config.json"

# 日志初始化
import os
from datetime import datetime
log_dir = os.path.join(os.path.dirname(__file__), "log")
os.makedirs(log_dir, exist_ok=True)
log_time = datetime.now().strftime("%Y%m%d_%H%M")
log_file = os.path.join(log_dir, f"app_{log_time}.log")
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler(log_file, encoding='utf-8')
    ]
)
logger = logging.getLogger(__name__)

def get_resolution():
    try:
        with open(CONFIG_PATH, "r") as f:
            config = json.load(f)
            width = config.get("width", 1024)
            height = config.get("height", 600)
            logger.info(f"读取分辨率: {width}x{height}")
            return width, height
    except Exception as e:
        logger.warning(f"读取分辨率失败，使用默认值: {e}")
        logger.error(traceback.format_exc())
        return 1024, 600

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Hello World")
        from PySide6.QtWidgets import QPushButton, QWidget, QVBoxLayout
        from src.soft_keyboard import SoftKeyboard

        central_widget = QWidget()
        layout = QVBoxLayout(central_widget)

        self.lineedit = QLineEdit()
        self.lineedit.setPlaceholderText("请输入内容...")
        self.lineedit.setFixedHeight(60)
        self.lineedit.setStyleSheet("font-size: 32px; background: #fff; border-radius: 10px;")
        layout.addWidget(self.lineedit, alignment=Qt.AlignCenter)

        button = QPushButton("Hello World")
        button.setStyleSheet("font-size: 48px; color: #222; background: #fff; border-radius: 20px; padding: 40px 80px;")
        layout.addWidget(button, alignment=Qt.AlignCenter)

        self.setCentralWidget(central_widget)
        self.setStyleSheet("background: white;")

        self.soft_keyboard = SoftKeyboard()
        self.lineedit.installEventFilter(self)

    def eventFilter(self, obj, event):
        if obj == self.lineedit and event.type() == event.FocusIn:
            self.soft_keyboard.set_target(self.lineedit)
            self.soft_keyboard.show_keyboard()
        return super().eventFilter(obj, event)

if __name__ == "__main__":
    try:
        logger.info("应用启动中...")
        app = QApplication(sys.argv)
        width, height = get_resolution()
        window = MainWindow()
        window.resize(width, height)
        window.show()
        logger.info(f"窗口已显示，分辨率: {width}x{height}")
        sys.exit(app.exec())
    except Exception as e:
        logger.error(f"程序运行异常: {e}")
        logger.error(traceback.format_exc())
